
var GridView = new Class({
  generateInnerRow: function(row) {
    var s = "";
    row.each(function(item) {
      // FIXME: allow customization of item view
      s += '<td>' + item + '</td>';
    });
    return s;
  },
  generateInnerSection: function(data, prefix, a, cols, depth) {
    var s = "";
    if(data.inner.length>0) {
      if(depth>0) {
        prefix += '<td rowspan="' + data.inner.length 
               + '" colspan="' + depth + '" class="filler"></td>';
      }
      data.inner.each(function(item, id) {
        s += '<tr';
        if(id%2==1) s+= ' class="odd"';
        s+= '>' + prefix + this.generateInnerRow(item) + '</tr>';
        prefix = "";
      },this);
    }
    data.section.each(function(item,id) {
      s += '<tr class="section">' + prefix
        + '<td colspan="' + (cols+depth) +'">' + item.name
        + '</td></tr>'
        + this.generateInnerSection(item,
            '<td rowspan=' + a.section[id].total + '" class="extenser"></td>',
            a.section[id], cols, depth-1);
      prefix = "";
    },this);
    return s;
  },
/*  generateSection: function(data, a, cols, depth) {
    return '<tr class="section"><td colspan="' + (cols+depth) +'">'
      + data.name + '</td></tr>' + this.generateInnerSection(data, a, cols, depth);
  },*/
  // calculate depth, cols and mainly the number of row by section
  analyseData: function(data) {
    var depth=0;
    var cols=0;
    if(data.inner.length>0) {
      cols=data.inner[0].length;
    }
    var rows={ total: data.inner.length, section: [] };
    data.section.each(function(item) {
      r = this.analyseData(item);
      depth = Math.max(depth, r.depth+1);
      cols = Math.max(cols, r.cols);
      rows.section.push(r.rows);
      rows.total += r.rows.total+1;
    },this);
    return { depth: depth, cols: cols, rows: rows };
  },
  generateTable: function(data) {
    var analyse = this.analyseData(data);
//    console.log(analyse);

    // FIXME: finish the header generation
    var s = '<table><tr><th colspan="' + analyse.depth + '"></th></td>'
      + this.generateInnerSection(data,"",analyse.rows,
          analyse.cols,analyse.depth);

//    console.log(s);

    return s+"</table>";
  },

  initialize: function() {
    $('gw').set('html', this.generateTable(ex_data));
  }
});
